﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml.Serialization;

namespace Eugenhome.Atrium
{
    /// <summary>
    /// 
    /// </summary>
    public class DAO
    {
        /// <summary></summary>
        public const string WEBCONFIG_HOSTINGPROXY_KEY = "HostingProxy";
        /// <summary></summary>
        public const string WEBCONFIG_MAILMETHOD_KEY = "MailMethod";
        /// <summary></summary>
        public const string WEBCONFIG_MAILMETHOD_VALUE_ATOM = "atom";
        /// <summary></summary>
        public const string WEBCONFIG_MAILMETHOD_VALUE_IMAP = "imap";
        /// <summary></summary>
        public const string IMAGE_CONNECTED = "gui/connected.gif";
        /// <summary></summary>
        public const string IMAGE_DISCONNECTED = "gui/disconnected.gif";

        /// <summary></summary>
        [XmlIgnore]
        public List<string> Errors = new List<string>();

        /// <summary></summary>
        public static DateTime ClientDateTimeNow
        {
            get
            {
                TimeZoneInfo ownerTzi = TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time");
                TimeZoneInfo localTzi = TimeZoneInfo.Local;

                return DateTime.Now.AddHours(localTzi.BaseUtcOffset.Hours - ownerTzi.BaseUtcOffset.Hours);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="type"></param>
        /// <param name="privateKey"></param>
        public void Save(string filename, object obj, string privateKey)
        {
            Errors.Clear();

            XmlSerializer serializier = new XmlSerializer(obj.GetType());

            if (privateKey == null || privateKey.Equals(string.Empty))
            {
                string tempfilename = Path.Combine(Path.GetDirectoryName(filename), filename + ".tmp");

                if (File.Exists(tempfilename)) File.Delete(tempfilename);

                TextWriter writer = new StreamWriter(tempfilename, false, Encoding.UTF8);
                try
                {
                    serializier.Serialize(writer, obj);
                    writer.Close();

                    if (File.Exists(filename)) File.Delete(filename);

                    File.Move(tempfilename, filename);
                }
                catch (Exception ex)
                {
                    Errors.Add("Fehler beim Speichern: " + ex.Message);
                    writer.Close();
                }
            }
            else
            {
                CCryptography cry = new CCryptography(privateKey);
                try
                {
                    Stream s = new MemoryStream();
                    serializier.Serialize(s, obj);
                    byte[] bufferOut = cry.Encrypt(s);

                    FileStream fs = File.Open(filename, FileMode.Create, FileAccess.Write);
                    fs.Write(bufferOut, 0, bufferOut.Length);
                    fs.Close();
                }
                catch (Exception ex)
                {
                    Errors.Add("Fehler beim Speichern: " + ex.Message);
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="type"></param>
        /// <param name="privateKey"></param>
        public object Load(string filename, Type type, string privateKey)
        {
            Errors.Clear();

            object loadedobj = null;

            try
            {
                XmlSerializer serializier = new XmlSerializer(type);

                if (privateKey == null || privateKey.Equals(string.Empty))
                {
                    TextReader reader = new StreamReader(filename);
                    loadedobj = serializier.Deserialize(reader);
                    reader.Close();
                }
                else
                {
                    CCryptography cry = new CCryptography(privateKey);
                    FileStream fs = File.Open(filename, FileMode.Open, FileAccess.Read);
                    byte[] daten = new byte[(int)fs.Length];
                    fs.Read(daten, 0, (int)fs.Length);
                    fs.Close();

                    byte[] datenOut = cry.Decrypt(daten);
                    Stream s = new MemoryStream(datenOut);
                    loadedobj = serializier.Deserialize(s);
                }
            }
            catch (Exception ex)
            {
                Errors.Add("Fehler beim Datenladen:" + ex.Message);
            }

            return loadedobj;
        }

    }
}
